﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Security;
using Sok.Munkae.ApplicationServices;
using Sok.Munkae.ApplicationServices.Membership;
using Sok.Munkae.Tenant;

namespace Sok.Munkae.Web.FormsAuthentication
{

    public class FormsAuthenticationProvider : IAuthenticationProvider
    {
        private IHostNameProvider hostNameProvider;

        public FormsAuthenticationProvider(IHostNameProvider hostNameProvider)
        {
            this.hostNameProvider = hostNameProvider;
        }
        public virtual void SetAuthCookie(string userName, bool createPersistentCookie)
        {
            var authTicket = new FormsAuthenticationTicket(userName, createPersistentCookie, 9);
            var authCookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, System.Web.Security.FormsAuthentication.Encrypt(authTicket))
                                 {
                                     Expires = DateTime.Now.AddMinutes(9),
                                     Domain = hostNameProvider.GetDomainName(),
                                     HttpOnly = true
                                 };
            HttpContext.Current.Response.Cookies.Add(authCookie);
            
        }

        public virtual void SignOut()
        {
            System.Web.Security.FormsAuthentication.SignOut();
            var authCookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName)
                                 {
                                     Expires = DateTime.Now.AddDays(-1),
                                     Domain = hostNameProvider.GetDomainName(),
                                     HttpOnly = true
                                 };
            HttpContext.Current.Response.Cookies.Add(authCookie);
        }
        
        public virtual void RedirectToLogin()
        {
            HttpContext.Current.Response.Redirect(
                System.Web.Security.FormsAuthentication.LoginUrl +
                string.Format("?ReturnUrl={0}", HttpContext.Current.Request.Url.AbsolutePath), true);
        }
    }

}
